package com.zt.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zt.common.dtos.ResponseResult;
import com.zt.common.enums.AppHttpCodeEnum;
import com.zt.pojo.ApUser;
import com.zt.service.ApUserService;
import com.zt.mapper.ApUserMapper;
import com.zt.util.JwtToken;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
* @author dell
* @description 针对表【ap_user(APP用户信息表)】的数据库操作Service实现
* @createDate 2024-09-06 19:52:45
*/
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser>
    implements ApUserService{

    @Resource
    private ApUserMapper mapper;
    @Override
    public ResponseResult login(ApUser apUser) {
//        1.校验参数是否有效
        if(StringUtils.isEmpty(apUser)){
//            参数无效返回报错
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

//        2.根据用户名称查询
        ApUser one = mapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getName, apUser.getName()));
//      2.1 判断用户是否存在
        if(one==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        3.比对密码
        String password = apUser.getPassword();
        String salt = one.getSalt();
        String s = DigestUtils.md5DigestAsHex((password+salt ).getBytes());
        if(!one.getPassword().equals(s)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
//        如果用户存在且密码正确则生成token
        Map<String,Object> map=new HashMap<>();
        map.put("token",one.getId());
        String jetToken = JwtToken.createJetToken(map);

        return ResponseResult.okResult(jetToken);
    }
}




